<?php 
namespace Wdl\helper;

class VillageHelper{

    /**
     * 获取小区/商圈的房源数量统计
     * @param   $title =区域+小区名称/商圈名称
     */
    public static function get_village_house_nums($area,$title, $isstr = true)
    {
        global $_W ;
        $rows = pdo_fetchall(
                "select * from ".tablename("kbwdl_count") 
                ." where  `uniacid` = :uniacid AND title=:title AND nums>0",
                ['title'=>$area.$title,'uniacid' => webHelper::bindUniacid() ]
            );
        $data = [];
        foreach($rows as $row){
            $data[ $row['house_type'] ] = $row['nums'];
        }
        $m = webHelper::house_type();    
        $str = ""; $count = 0;   
        foreach($m as $key=> $item){
             if(isset($data[ $item['zhutype']])) {
                $count = $count +  $data[ $item['zhutype']];
                $str.= sprintf('<a href="%s"><span>%s[%s]</span></a>', 
                            webHelper::WebUrl('sendlist',['op'=> $key,'area'=> $area,'keyword'=>$title]),
                            $item['name'], 
                            $data[ $item['zhutype']]
                        );
             }
        }
        if($isstr)
            return $str;
        return $count;
    }
    public static function get_area_data($id)
    {
        global $_W, $_GPC;
        
        $condition = ' WHERE `uniacid` = :uniacid AND id=:id ';
        $params = array('id'=>$id,'uniacid' => webHelper::bindUniacid());

        $info =  pdo_fetch("select * from ". tablename('kbwdl_area'). $condition, $params);
 
        //格式化地图坐标为数组
        if(!empty($info['point'])){
            $p = explode(",",$info['point']);
            $info['lng'] = $p[0];
            $info['lat'] = isset($p[1])? $p[1] :"0";
        }
        
        return $info;
    }
    /**
     * @return int village_id
     */
    public static function save_village($area,$village_name)
    {
        if( empty($village_name)){
            return false;
        }  
        $savedata['name'] = $village_name;
        $savedata['area'] = $area;
        $savedata['parent_id'] = 1;
         
        return self::save_area_post(0,3, $savedata);
    }
    /** 
     * id>0的时候是编辑，如果name相同，会覆盖id 进行编辑
     */
    public static function save_area_post($id, $type = 3,   $savedata =[])
    {
        global $_W, $_GPC;
        $uniacid = webHelper::bindUniacid() ; 
        $savedata['uniacid'] = $uniacid;
        $savedata['type'] = $type;
        $mapoint = [];
        if(!empty($savedata['point']['lat']) && !empty($savedata['point']['lng'])){
            $mapoint['lat'] = $savedata['point']['lat'];
            $mapoint['lng'] = $savedata['point']['lng'];
            $savedata['point'] = sprintf("%s,%s", $mapoint['lng'], $mapoint['lat']);

        } else{
            $savedata['point'] = '';
            if(!$id){
                unset($savedata['point']);
            }
        } 
       
        //检测重复
        $info =  pdo_fetch("select * from ". tablename('kbwdl_area')."where name=:name and  uniacid=:uniacid and `type`=:type",
                        ['uniacid'=> $uniacid, 'name' => $savedata['name'],'type'=>$type ] 
                    );
        if($info) $id = $info['id'];
        /*保存数据*/
        if( $id >0 ){
        /**/
            pdo_update( "kbwdl_area", 
                $savedata, 
                array('uniacid' => $uniacid,'id'=>  $id )           
            );
            $focus = false;
            if($savedata['point'] && $info['point'] !== $savedata['point']) 
                $focus = true;
             
            VillageHelper::village_map_lbs_data($mapoint, $id , $focus);
        }else{
            pdo_insert( "kbwdl_area" , $savedata);
            $id = pdo_insertid();

            VillageHelper::village_map_lbs_data($mapoint, $id );
        } 
        /**把地图数据保存 */
        
        return $id;    
    }
    public static function has_lbs_data($village_id)
    {
        return webHelper::fetch_place_data('village_mapdata','', $village_id);
        // return pdo_fetchall("select * from ".tablename('kbwdl_config') .
        //         " where placeid=:id and `module`='village_mapdata' ", 
        //         ['id'=> $village_id]);
    }
    /** 
     * 保存小区的lbs地图周边数据
     */
    public static function village_map_lbs_data($mapoint, $id ,$isfoce = false)
    {
        //因为后台存的都是百度地图坐标
        $point =  sprintf("%s,%s", $mapoint['lng'], $mapoint['lat']);
        if(strlen($point) < 3) return ;
        //转换成腾讯坐标
        $point = VillageHelper::baidu_map_txmap($point);
        $point = explode(",", $point);
        $mapoint['lng'] = $point[0];
        $mapoint['lat'] = $point[1];
        $config = webHelper::fetch_place_data('setting','display');

        $mapsearch = new MapSearch($config['txmap_key'], $config['txmap_sk']);
        //lat = 25.10222 ,lng = 101.5352
        if(!empty($mapoint) ){
            $has = pdo_fetch("select * from ".tablename("kbwdl_config")." WHERE placeid=:placeid",['placeid'=> $id]);
            if(empty($has) || $isfoce){
                //没有记录，或者，强制更新
                set_time_limit(600);               
                foreach($mapsearch->category as $keyword => $v){
                    $p1 = $mapsearch->keyword($keyword, $mapoint['lat'], $mapoint['lng']);
                    if($p1){
                        webHelper::update_place_data('village_mapdata', $keyword,$p1,$id);
                    }    
                }
            }             
        }

    }
    /** 
     * 百度坐标转换成腾讯地图坐标
     */
    public static function baidu_map_txmap($point)
    {
        if(strlen($point)<22){  
            $point = explode(",", $point);
          
            $bd_lon  = floatval($point[0]); 
            $bd_lat  = floatval($point[1]); 
            $X_PI = M_PI * 3000.0 / 180.0;  
            $x = $bd_lon - 0.0065;  
            $y = $bd_lat - 0.006;  
            $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $X_PI);  
            $theta = atan2($y, $x) - 0.000003 * cos($x * $X_PI);  
            $lon = $z * cos($theta);  
            $lat = $z * sin($theta); 
            $mapinfo = $lon.",".$lat;   
            return $mapinfo;
        } 
        return $point;
    }
}